package com.clss.commandhelper.tools;

import android.app.Activity;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.clss.commandhelper.CommandHelperApplication;
import com.clss.commandhelper.base.BaseActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;


/**
 * 一般工具类
 * Created by harisucici on 2017/6/13.
 */

public class Utils {
    private static final String TAG = "Tools";
    public static Toast toast;
    public static void showOneToast(Context context, String msg) {
        if(toast == null){
            toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        }else{
            toast.setText(msg);
        }
        toast.show();
    }
    public static String encode(String s){
        String result = "";
        try {
            result = URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getNowTime() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH:mm");
//        java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat("HH:mm");
        return formater.format(new Date());
    }

    public static String getNowTimeToRecord() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return formater.format(new Date());
    }

    public static String timeToDate(long time) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formater.format(time);
    }
    public static String timeToDate(String time) {
        try{
            Long aLong = Long.valueOf(time);
            SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return formater.format(aLong);
        }catch (NumberFormatException e){
            return time;
        }
    }

    public static String dateToTime(String date){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        String time = "";
        try {
            Date d = dateFormat.parse(date);
            time = timeFormat.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static String getStampToTime(long stamp){
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return timeFormat.format(new Date(stamp));
    }

    /**
     * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
     *
     * @param time
     *            需要格式化的时间 如"2014-07-14 19:01:45"
     * @return time为null，或者时间格式不匹配，输出空字符""
     */
    public static String formatDisplayTime(long time) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != 0) {
            String pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(timeToDate(time));
                Date today = new Date();
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
                    } else {
                        if (dTime < tMin) {
                            display = "刚刚";
                        } else if (dTime < tHour) {
                            display = (int) Math.ceil(dTime / tMin) + "分钟前";
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            display = (int) Math.ceil(dTime / tHour) + "小时前";
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = timeToDate(tDate.getTime());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return display;
    }


    /**
     * 打开扬声器
     */
    public static void openSpeaker(Context context) {
        String m = Build.MANUFACTURER;
        try{
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (!m.toLowerCase().contains("xiaomi")){
                audioManager.setMode(AudioManager.ROUTE_SPEAKER);
            }
            int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
            if(!audioManager.isSpeakerphoneOn()) {
//                setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL.
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                audioManager.setSpeakerphoneOn(true);
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL ),
                        AudioManager.STREAM_VOICE_CALL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭扬声器
     */
    public static void closeSpeaker(Context context) {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if(audioManager != null) {
                if(audioManager.isSpeakerphoneOn()) {
                    audioManager.setSpeakerphoneOn(false);
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,0,
                            AudioManager.STREAM_VOICE_CALL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 听筒静音
     */
    public static void closeListener(Context context){
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if(audioManager != null) {
            audioManager.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, AudioManager.FLAG_SHOW_UI);
        }
    }

    /**
     * base64 互转
     */
    public static Bitmap Base642Bitmap(String s) {
        byte[] bytes = Base64.decode(s, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static String Bitmap2Base64(Bitmap bit){
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 80, bos);//参数100表示不压缩
        byte[] bytes=bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 图片加载工具Glide加入token
     */
    public static void showUrlImage(Context context, String url, ImageView imageView){
        Glide.with(context)
                .load(new GlideUrl(url
                        , new LazyHeaders
                        .Builder()
                        .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                        .build()))
                .into(imageView);
    }

    /**
     * 加载本地视频缩略图
     * @param context
     * @param videoId
     * @param imageView
     */
    public static void showVideoThumbnail(Context context, String videoId, ImageView imageView){
        Glide.with(context)
                .load(Uri.fromFile(new File(SdCard.getVideo(),videoId+".mp4")))
                .into(imageView);
    }

    /**
     * 图片加载工具Glide加入token
     */
    public static void showUrlImage(Fragment fragment, String url, final ImageView imageView){
        Glide.with(fragment)
                .load(new GlideUrl(url
                        , new LazyHeaders
                        .Builder()
                        .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                        .build()))
//                .into(imageView);
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    //加载圆角图片
//    public static void loadRoundImage(Context context, String url, final ImageView imageView) {
//        Glide.with(context)
//                .load(new GlideUrl(url,
//                        new LazyHeaders
//                                .Builder()
//                                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
//                                .build()))
//                .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(10, 0)))
//                .into(imageView);
//    }


    //加载圆形图片
//    public static void loadCirclePic(final Context context, String url, final ImageView imageView) {
//        Glide.with(context)
//                .load(url)
//                .asBitmap()
//                .placeholder(placeholder)
//                .error(placeholder)
//                .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
//                .into(new BitmapImageViewTarget(imageView) {
//                    @Override
//                    protected void setResource(Bitmap resource) {
//                        RoundedBitmapDrawable circularBitmapDrawable =
//                                RoundedBitmapDrawableFactory.create(context.getResources(), resource);
//                        circularBitmapDrawable.setCircular(true);
//                        imageView.setImageDrawable(circularBitmapDrawable);
//                    }
//                });
//
//    }

    /**
     netType = 2 为移动网络
     netType = 1 为WiFi网络
     nteType = 0 为无网络
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE){
            netType = 2;
        }else if (nType == ConnectivityManager.TYPE_WIFI){
            netType = 1;
        }
        return netType;
    }

    /**
     * 获取屏幕的宽度px
     *
     * @param context 上下文
     * @return 屏幕宽px
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
        return outMetrics.widthPixels;
    }

    /**
     * 获取屏幕的高度px
     *
     * @param context 上下文
     * @return 屏幕高px
     */
    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
        return outMetrics.heightPixels;
    }

    /**
     * convert dp to its equivalent px
     *
     * 将dp转换为与之相等的px
     */
    public static int dp2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    /**
     * convert px to its equivalent sp
     *
     * 将px转换为sp
     */
    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * convert sp to its equivalent px
     *
     * 将sp转换为px
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取location中的具体地址
     * @param locationString
     * @return
     */
    public static String getLocationAddress(String locationString){
        int begin = locationString.indexOf("#address=");
        int end = locationString.indexOf("#country=");
        String address = "";
        if (begin > 0 && end > 0){
            address = locationString.substring(begin + 8, end - 1);
        }
        return address;
    }

    /**
     * 从38.024059,114.434081形式的坐标中取出内容
     * @param latlng
     * @return
     */
//    public static LatLng getLatLngFromString(String latlng){
//        String[] latlong = latlng.split(",");
//        double latitude = Double.parseDouble(latlong[1]);
//        double longitude = Double.parseDouble(latlong[0]);
//        return new LatLng(latitude, longitude);
//    }
//
//    public static int checkFileType(String path) {
//        if (path.contains(".mp4") || path.contains(".avi") || path.contains(".3gp")) {
//            return Constant.TYPE_VIDEO;
//        }
//        if (path.contains(".mp3") || path.contains(".aac") || path.contains(".amr")) {
//            return Constant.TYPE_VOICE;
//        }
//        if (path.contains(".png") || path.contains(".jpg")) {
//            return Constant.TYPE_IMAGE;
//        }
//        return -1;
//    }
//
//    public static ReciveMessageEntity getReceiveMsgInfo(String text){
//        if (text.contains(Constant.SEND_IMAGE_MSG_TAG_START)){
//            return new ReciveMessageEntity(text
//                    .replace(Constant.SEND_IMAGE_MSG_TAG_START, "")
//                    .replace(Constant.SEND_IMAGE_MSG_TAG_END, "")
//                    , Constant.TYPE_IMAGE);
//        }else if (text.contains(Constant.SEND_VIDEO_MSG_TAG_START)){
//            return new ReciveMessageEntity(text
//                    .replace(Constant.SEND_VIDEO_MSG_TAG_START, "")
//                    .replace(Constant.SEND_VIDEO_MSG_TAG_END, "")
//                    , Constant.TYPE_VIDEO);
//        }else if (text.contains(Constant.SEND_VOICE_MSG_TAG_START)){
//            return new ReciveMessageEntity(text
//                    .replace(Constant.SEND_VOICE_MSG_TAG_START, "")
//                    .replace(Constant.SEND_VOICE_MSG_TAG_END, "")
//                    , Constant.TYPE_VOICE);
//        }else {
//            return new ReciveMessageEntity("", -1);
//        }
//    }

    /**
     * 获取activity的view
     */
    public static View getContentView(Activity context){
        return ((ViewGroup)context.findViewById(android.R.id.content)).getChildAt(0);
    }

    /**
     * 验证手机号码
     * 现有手机号段:
     移动：139   138   137   136   135   134   147   150   151   152   157   158    159   178  182   183   184   187   188
     联通：130   131   132   155   156   185   186   145   176
     电信：133   153   177   173   180   181   189
     虚拟运营商：
     170  171
     */
    public static boolean checkMobileNumber(String mobileNumber){
        boolean flag = false;
        try{
            Pattern regex = compile("^((13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8})$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 检查系统是否有downloadmanager
     * @param context
     * @return
     */
    public static boolean canDownloadState(Context context) {
        try {
            int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 开启新的activity并传值
     * @param fromActivity
     * @param toActivity
     */
    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity){
        startActivity(fromActivity, toActivity, null);
    }

    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity,
                                     @Nullable Bundle bundle){
        startActivity(fromActivity, toActivity, bundle, false);
    }

    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity,
                                     @Nullable Bundle bundle, boolean finishThisActivity){
        Intent intent = new Intent(fromActivity, toActivity);
        if (null != bundle){
            bundle.putString(Constant.ACTIVITY_NAME, fromActivity.getClass().getSimpleName());
            intent.putExtras(bundle);
        }else {
            Bundle b = new Bundle();
            b.putString(Constant.ACTIVITY_NAME, fromActivity.getClass().getSimpleName());
            intent.putExtras(b);
        }
        fromActivity.startActivity(intent);
        if (finishThisActivity){
            fromActivity.finish();
        }
    }

    /**
     * 从通讯录选择联系人
     * @param activity
     * @param uri
     * @return
     */
    public static String[] getPhoneContacts(Activity activity, Uri uri){
        String[] contact = new String[2];
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if(cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if(phone != null){
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }


    /****
     * 动态设置listview高度
     ****/
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 设定edittext是否显示密码内容
     * @param editText
     * @param isHide
     */
    public static void setEditTextPasswordType(EditText editText, boolean isHide){
        editText.setInputType(isHide ?
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD :
                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

    /**
     * 获取版本号
     *
     * @return
     */

    public static String getVersionCode() {
        PackageInfo info = null;
        Context context = CommandHelperApplication.getAppContext();
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info.versionCode + "";
    }

    public static String getVersionName() {
        PackageInfo info = null;
        Context context = CommandHelperApplication.getAppContext();
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info.versionName + "";
    }

    public static String listToString(List<String> list){
        if(list == null){
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(String string :list) {
            if(first) {
                first = false;
            }else{
                result.append(", ");
            }
            result.append(string);
        }
        return result.toString();
    }

    public static int checkFileType(String path) {
        if (path.contains(".mp4") || path.contains(".avi") || path.contains(".3gp")) {
            return Constant.TYPE_VIDEO;
        }
        if (path.contains(".mp3") || path.contains(".aac") || path.contains(".amr")) {
            return Constant.TYPE_VOICE;
        }
        if (path.contains(".png") || path.contains(".jpg")) {
            return Constant.TYPE_IMAGE;
        }
        return -1;
    }
//    public static boolean isBadJson(String json) {
//        return !isGoodJson(json);
//    }
//
//    public static boolean isGoodJson(String json) {
//        if (StringUtils.isBlank(json)) {
//            return false;
//        }
//        try {
//            new JsonParser().parse(json);
//            return true;
//        } catch (JsonParseException e) {
//
//            return false;
//        }
//    }

    public static void openLocalVideo(Context context, String videoPath){
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        Uri data = Uri.parse("file://"+videoPath);
        intent.setDataAndType(data, "video/mp4");
        context.startActivity(intent);
    }
    public static boolean isNull(Object object){
        if (object == null || object.toString().trim().equals(""))
            return true;
        return false;
    }

    /**
     * 调用拨号界面
     * @param phone 电话号码
     */
    public static void callToSystem(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
